package logic

import (
	"context"
	"errors"
	"product/model/mysql"

	"product/productrpc/internal/svc"
	"product/productrpc/productrpc"

	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/gorm"
)

type ShopUpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewShopUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ShopUpdateLogic {
	return &ShopUpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ShopUpdateLogic) ShopUpdate(in *productrpc.ShopUpdateRequest) (*productrpc.ShopUpdateResponse, error) {
	// todo: add your logic here and delete this line

	var shop mysql.Shop
	mysql.DB.Debug().Where("id = ?", in.ShopId).Find(&shop)
	if shop.ID != 0 {
		return nil, errors.New("商品不存在，请更换")
	}

	var shops mysql.Shop
	mysql.DB.Debug().Where("id = ?", in.ShopId).Find(&shops)
	if shops.ID == 0 {
		return nil, errors.New("商品不存在，修改失败")
	}

	m := mysql.Shop{
		Model:     gorm.Model{ID: uint(in.ShopId)},
		ShopName:  in.ShopName,
		ShopPrice: float64(in.ShopPrice),
	}

	err := mysql.DB.Debug().Updates(&m).Error
	if err != nil {
		return nil, err
	}
	return &productrpc.ShopUpdateResponse{
		ShopId: int64(m.ID),
	}, nil
}
